package I.O;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileUtils {

	/**
	 * 文件拷贝
	 * 
	 * @author 智洋
	 * @param src
	 *            源文件
	 * @param dest
	 *            目标文件路径
	 * @return
	 * @throws FileNotFoundException,IOException
	 */
	public static void fileCopy(File src, File dest) throws FileNotFoundException, IOException {
		FileInputStream inf = null;
		FileOutputStream wf = null;
		try {
			if (!src.isFile()) {
				System.out.println("文件夹不能拷贝");
				throw new IOException("文件夹不能拷贝");
			}
			inf = new FileInputStream(src);
			wf = new FileOutputStream(dest);
			int c;
			while ((c = inf.read()) != -1) {
				wf.write(c);
			}
			wf.flush();
		} catch (FileNotFoundException e) {
			throw e;
		} catch (IOException e) {
			throw e;
		} finally {
			try {
				if (null != inf) {
					inf.close();
				}
				if (null != inf) {
					wf.close();
				}
			} catch (IOException e) {
				throw e;
			}

		}
	}

	/**
	 * 复制文件夹 
	 * @author 智洋
	 * @param f1
	 * @param f2
	 * @throws FileNotFoundException
	 * @throws IOException
	 */
	public static void copyDir(File f1, File f2) throws FileNotFoundException, IOException {
		if (f1.isDirectory()) {
			f2 = new File(f2, f1.getName());
			System.out.println(f1.getName());
			copyDirDetail(f1, f2);
		}
	}

	public static void copyDirDetail(File f1, File f2) throws FileNotFoundException, IOException {

		if (f1.isFile()) {
			FileUtils.fileCopy(f1, f2);
		} else if (f1.isDirectory()) {
			f2.mkdirs();
			for (File sub : f1.listFiles()) {
				System.out.println(sub.getName());
				copyDirDetail(sub, new File(f2, sub.getName()));
			}
		}
	}
}
